#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: menu.py
@time: 2023/11/14 19:24
@desc: 
"""

from backend.tvadmin.system.models.factory import Factory
from backend.tvadmin.system.models.permission import Menu
from backend.tvadmin.utils.base_requeset import BaseAuthCheckHttpHandler
from backend.tvadmin.utils.base_response import SuccessResponse, ErrorResponse
from backend.tvadmin.utils.page_utils import self_pagination


class MenuModelViewSet(BaseAuthCheckHttpHandler):
    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = Menu.filter_list(self.request.data)
        else:
            result = Factory.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        """
        菜单添加
        """
        menu = Menu()
        menu.name = self.request.data.get("name")
        menu.sort = self.request.data.get("sort")
        menu.is_catalog = self.request.data.get("is_catalog")
        menu.web_path = self.request.data.get("web_path")
        menu.interface_method = self.request.data.get("interface_method")
        if self.request.data.get("parent_id"):
            menu.parent_id = self.request.data.get("parent_id")
        menu = Menu.add(menu, self.request)

        return self.write(SuccessResponse(menu))

    def put(self, *args, **kwargs):
        id = self.request.data.get("id")
        if id:
            factory = Factory.first(id=id)
            if factory:
                Factory.filter_update(filter_args={"id": id}, update_args=self.request.data, request=self.request)
                factory = Factory.query_first_dict(id=id)
                return self.write(SuccessResponse(data=factory))
            else:
                return self.write(ErrorResponse(msg="岗位不存在"))

    def delete(self, *args, **kwargs):
        id = self.request.data.get("id")
        factory = Factory.first(id=id)
        if factory:
            Factory.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="工厂不存在"))
